package cn.ichiva.puppet.example.postwoman;


import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WSServer extends WebSocketServer {
    private static final  org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(WSServer.class);

    static Map<WebSocket,WebSocket> sessions = new ConcurrentHashMap<>();

    public WSServer(InetSocketAddress address) {
        super(address);
    }


    @Override
    public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
        sessions.put(webSocket,webSocket);

        log.info("接入: size = {}",sessions.size());
    }

    @Override
    public void onClose(WebSocket webSocket, int i, String s, boolean b) {
        sessions.remove(webSocket.getSSLSession());

        log.info("断开: size = {}",sessions.size());
    }

    @Override
    public void onMessage(WebSocket webSocket, String message) {
        log.info("收到: message = {}",message);

        webSocket.send("收到:[" + message + "]over");
    }

    @Override
    public void onError(WebSocket webSocket, Exception e) {
        log.error("出错:",e);
    }

    @Override
    public void onStart() {
        log.info("WS服务已启动: address = {}","ws://127.0.0.1:" + getAddress().getPort());
    }

    public static void main(String[] args) {
        new WSServer(new InetSocketAddress(11219)).start();
    }
}
